<?php
namespace app\integral\model;

use app\BaseModel;
use app\member\model\Member;
use app\shop\model\AdminShopOrderGoods;
use think\facade\Db;

class Integral extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_integral_integral_list';


    protected  $append = [

        'show_price',

        'all_stock',

        'all_have_stock',

        'goods_info',

    ];


    /**
     * @author chenniang
     * @DataTime: 2021-10-29 18:52
     * @功能说明:参与活动的商品规格信息
     */
    public function getGoodsInfoAttr($value,$data){

        if(!empty($data['id'])&&!empty($data['goods_type'])){

            $i_model = new IntegralGoods();

            if($data['goods_type']==1){

                $list = $i_model->alias('a')
                    ->join('longbing_card_shop_spe_price b','a.spe_id = b.id')
                    ->where(['a.atv_id' => $data['id']])
                    ->field(['b.stock as goods_stock','b.price as goods_price','a.*'])
                    ->select()
                    ->toArray();
            }else{

                $list = $i_model->alias('a')
                    ->join('longbing_card_coupon b','a.spe_id = b.id')
                    ->where(['a.atv_id' => $data['id']])
                    ->field(['b.number as goods_stock','b.reduce','b.full','a.*'])
                    ->select()
                    ->toArray();
            }

            return $list;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-29 18:46
     * @功能说明:获取第一个规格的价格
     */
    public function getShowPriceAttr($value,$data){

        if(!empty($data['id'])){

            $i_model = new IntegralGoods();

            $info = $i_model->dataInfo(['atv_id'=>$data['id']]);

            $text = '';

            if(isset($info['integral'])&&$info['integral']>0){

                $text .= $info['integral'].'积分';
            }

            if(isset($info['price'])&&$info['price']>0){

                $text .= '+'.$info['price'].'元';
            }

            return $text;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-29 18:50
     * @功能说明:总的库存
     */
    public function getAllStockAttr($value,$data){

        if(!empty($data['id'])){

            $i_model = new IntegralGoods();

            $num = $i_model->where(['atv_id'=>$data['id']])->sum('stock');

            return $num;
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-29 18:50
     * @功能说明:总的库存
     */
    public function getAllHaveStockAttr($value,$data){

        if(!empty($data['id'])){

            $i_model = new IntegralGoods();

            $num = $i_model->where(['atv_id'=>$data['id']])->sum('have_stock');

            return $num;
        }

    }
    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $goods_info = $data['goods_info'];

        unset($data['goods_info']);

        Db::startTrans();

        $res = $this->insert($data);

        $id = $this->getLastInsID();


        $res = $this->updateSome($id,$data,$goods_info);


        if(!empty($res['code'])){

            Db::rollback();

            return $res;
        }

        Db::commit();

        return $res;

    }






    /**
     * @author chenniang
     * @DataTime: 2021-10-29 18:21
     * @功能说明:
     */
    public function updateSome($id,$data,$goods_info){

        $i_model = new IntegralGoods();

        $atv = $this->dataInfo(['id'=>$id]);

        $arr = [];

        if(!empty($goods_info)){

            foreach ($goods_info as &$value){
                //检查该商品该规格同一时间段内有无其他活动
                $where = [];

                $where[] = ['a.goods_id','=',$data['goods_id']];

                $where[] = ['b.spe_id','=',$value['spe_id']];

                $where[] = ['a.status','>',-1];

                $where[] = ['a.id','<>',$id];

                $info = $i_model->alias('b')
                        ->join('longbing_card_integral_integral_list a','a.id = b.atv_id')
                        ->where($where)
                        ->field('a.*,b.*')
                        ->order('a.id desc')
                        ->select()
                        ->toArray();

                if(!empty($info)){

                    foreach ($info as $vs){

                       $res = is_time_cross($vs['start_time'],$vs['end_time'],$atv['start_time'],$atv['end_time']);

                        if($res==false){

                            return ['code'=>500,'msg'=>$vs['spe_name'].'该时间段已有积分活动，请先删除，再添加'];
                        }

                    }

                }

                $i_dis = [

                    'atv_id'  => $id,

                    'goods_id'=> $data['goods_id'],

                    'spe_id'  => $value['spe_id'],
                ];
                //查看是否已经有该活动
                $find = $i_model->dataInfo($i_dis);

                $insert = [

                    'uniacid' => $data['uniacid'],

                    'goods_id'=> $data['goods_id'],

                    'goods_type'=> $data['goods_type'],

                    'spe_id'  => $data['goods_type']==1?$value['spe_id']:$data['goods_id'],

                    'stock'   => $value['stock'],

                    'price'   => $value['price'],

                    'integral'=> $value['integral'],

//                    'have_stock'=> !empty($have_stock)?$have_stock:0,

                    'atv_id'  => $id,
                ];

                if(empty($find)){

                    $i_model->dataAdd($insert);

                    $arr[] = $i_model->getLastInsID();

                }else{

                    if($value['stock']<$find['have_stock']){

                        return ['code'=>500,'msg'=>'可兑换数量，不能小于已经兑换数量'];

                    }

                    $i_model->dataUpdate($i_dis,$insert);

                    $arr[] = $find['id'];

                }

            }

        }

        $i_model->where('id','not in',$arr)->where('atv_id','=',$id)->delete();

        return true;


    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        if(!empty($data['goods_info'])){

            $goods_info = $data['goods_info'];

            unset($data['goods_info']);
        }

        Db::startTrans();

        $res = $this->where($dis)->update($data);

        if(!empty($goods_info)){

            $res = $this->updateSome($dis['id'],$data,$goods_info);

            if(!empty($res['code'])){

                Db::rollback();

                return $res;
            }
        }

        Db::commit();

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('top desc,id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-29 13:34
     * @功能说明:积分列表可以通过商品名字查询
     */
    public function dataGoodsList($dis,$where,$page=10){

        $data = $this->alias('a')
                ->join('longbing_card_goods b','a.goods_id = b.id','left')
                ->join('longbing_card_coupon c','a.goods_id = c.id','left')
                ->where($dis)
                ->where(function ($query) use ($where){
                    $query->whereOr($where);
                })
                ->field('a.*,b.name as goods_name,cover,c.title')
                ->group('a.id')
                ->order('a.id desc')
                ->paginate($page)
                ->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['goods_name'] = $v['goods_type']==1?$v['goods_name']:$v['title'];
            }

        }

        return $data;


    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-29 13:54
     * @功能说明:初始化活动时间
     */
    public function initAtv(){

        $this->where('start_time','>',time())->update(['atv_status'=>1]);

        $this->where('start_time','<',time())->update(['atv_status'=>2]);

        $this->where('end_time','<',time())->update(['atv_status'=>3]);

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-01 10:18
     * @功能说明:正在进行中的活动
     */
    public function atvIng($goods_id,$spe_id=0,$goods_type=1){

//        $dis[] = ['a.atv_status','=',2];

        $dis[] = ['a.start_time','<',time()];

        $dis[] = ['a.end_time','>',time()];

        $dis[] = ['a.goods_id','=',$goods_id];

        $dis[] = ['a.status','=',1];

        $dis[] = ['a.goods_type','=',$goods_type];

        if(!empty($spe_id)){

            $dis[] = ['b.spe_id','=',$spe_id];
        }

        $data = $this->alias('a')
                ->join('longbing_card_integral_shop_goods b','a.id = b.atv_id')
                ->where($dis)
                ->field('b.goods_id,b.lock,b.spe_id,b.stock,b.price,b.integral,b.have_stock,b.id as shop_goods_id,a.*')
                ->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-01 10:18
     * @功能说明:正在进行中的活动列表
     */
    public function atvIngList($goods_id,$goods_type=1){

//        $dis[] = ['a.atv_status','=',2];

        $dis[] = ['start_time','<',time()];

        $dis[] = ['end_time','>',time()];

        $dis[] = ['goods_id','=',$goods_id];

        $dis[] = ['status','=',1];

        $dis[] = ['goods_type','=',$goods_type];

        $data = $this->where($dis)->select()->toArray();

        $arr = [];

        if(!empty($data)){

            foreach ($data as $v){

                if(!empty($v['goods_info'])){

                    foreach ($v['goods_info'] as $key=>$value){

                        $v['goods_info'][$key]['buy_limit'] = $v['buy_limit'];
                    }
                }

                $arr = array_merge($arr,$v['goods_info']);
            }
        }

        return array_values($arr);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-11-01 10:18
     * @功能说明:正在进行中的活动
     */
    public function buyLimit($goods_id,$spe_id=0,$goods_type=1){

//        $dis[] = ['a.atv_status','=',2];

        $dis[] = ['a.start_time','<',time()];

        $dis[] = ['a.end_time','>',time()];

        $dis[] = ['a.goods_id','=',$goods_id];

        $dis[] = ['a.status','=',1];

        $dis[] = ['a.goods_type','=',$goods_type];

       // $dis[] = ['a.buy_limit','=',0];

        if(!empty($spe_id)){

            $dis[] = ['b.spe_id','=',$spe_id];
        }

        $data = $this->alias('a')
            ->join('longbing_card_integral_shop_goods b','a.id = b.atv_id')
            ->where($dis)
            ->field('b.goods_id,b.lock,b.spe_id,b.stock,b.price,b.integral,b.have_stock,b.id as shop_goods_id,a.*')
            ->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-20 17:49
     * @功能说明:
     */
    public function payOrderInfo($goods){

        if(!empty($goods)){

            foreach ($goods as &$v){

//                dump($v);exit;

                $atv = $this->atvIng($v['goods_id'],$v['spe_price_id']);

                if(!empty($atv)){

//                    $v['i_price'] = $v['price']-$atv['price'];

                    $v['integral_price'] = $atv['price'];

                    $v['integral'] = $atv['integral'];


                }

            }

        }

        return $goods;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-20 13:38
     * @功能说明:获取正在进行活动中心商品id
     */
    public function getAtvIngGoods($uniacid,$type=1){

        $dis = [

            'uniacid'    => $uniacid,
            //1 商品 2优惠券
            'goods_type' => $type,

            'atv_status' => 2,

            'status'     => 1
        ];

        $goods_id = $this->where($dis)->column('goods_id');

        return $goods_id;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-04 14:41
     * @功能说明:获取是否
     */
    public function getBuyLimit($list){

        $data['buy_limit'] = 1;

        $data['discount_add'] = 1;

        foreach ($list as $value){

            $res = $this->buyLimit($value['goods_id'],$value['spe_price_id']);

            if(!empty($res)){

                if($res['buy_limit']==0){

                    $data['buy_limit'] = 0;
                }

                if($res['discount_add']==0){

                    $data['discount_add'] = 0;
                }

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-11 16:50
     * @功能说明:获取活动次数
     */
    public function getAtvNum1($id,$user_id){

        $order_model = new AdminShopOrderGoods();

        $dis = [

            'b.integral_id' => $id,

            'a.user_id'     => $user_id

        ];

        $num =  $order_model->alias('a')
                ->join('longbing_card_shop_order_item b','a.id = b.order_id')
                ->where('a.pay_type','>=',1)
                ->where($dis)
                ->sum('goods_num');

        return $num;

    }


    /**
     * @param $dis
     * @return float
     * 获取历史商品件数
     */
    public function getAtvNum($id,$user_id){

        $dis = [

            'a.integral_id' => $id,

            'b.user_id'     => $user_id

        ];

        $order_model = new AdminShopOrderGoods();

        //取消订单的不算 chen
        $num = $order_model->alias('a')
            ->join('longbing_card_shop_order b','a.order_id = b.id')
            ->where($dis)
            ->where('b.pay_type','>=',1)
            ->group('a.id')
            ->sum('a.goods_num');


        $order_id = $order_model->alias('a')
            ->join('longbing_card_shop_order b','a.order_id = b.id')
            ->where($dis)
            ->where('b.pay_type','>=',1)
            ->column('b.id');

        $order_refund_goods = new RefundOrderGoods();
        //申请退款成功的
        $refund_num = $order_refund_goods->where('order_id','in',$order_id)->where(['status'=>2])->sum('goods_num');

        return $num - $refund_num;

    }


    /**
     * @param $dis
     * @param $where
     * @param int $page
     * @功能说明:获取公司下面的商品
     * @author chenniang
     * @DataTime: 2022-01-20 14:14
     */
    public function companyGoodsList($dis,$where,$page=10){

        $data = $this->alias('a')
            ->join('longbing_card_goods b','a.goods_id = b.id')
            ->leftJoin('longbing_card_company_goods c' ,'b.id = c.goods_id')
            ->where($dis)
            ->where(function ($query) use ($where){
                $query->whereOr($where);
            })
            ->field(['a.*,b.name as goods_name,cover as goods_cover,b.price as goods_price'])
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;
    }


    /**
     * @param $dis
     * @param $where
     * @param int $page
     * @功能说明:获取公司下面的商品
     * @author chenniang
     * @DataTime: 2022-01-20 14:14
     */
    public function companyCouponList($dis,$where,$page=10){

        $data = $this->alias('a')
            ->join('longbing_card_coupon b','a.goods_id = b.id')
            ->leftJoin('longbing_card_coupon_company c' ,'b.id = c.coupon_id')
            ->where($dis)
            ->where(function ($query) use ($where){
                $query->whereOr($where);
            })
            ->field(['a.*,b.title,b.reduce,b.full,b.coupon_type,b.use_limit'])
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-20 16:23
     * @功能说明:获取商品或者卡券兑换条件
     */
    public function getDataCondition($user_id,$atv,$number,$type=4,$check_type=1){

        $member_model = new Member();

        $i_model = new \app\member\model\Integral();

        if(empty($atv)){

            return $check_type==1?0:2;
        }


        $member = $member_model->memberUpdateInfo(['user_id' => $user_id,'uniacid'=>$atv['uniacid']]);

        $user_integral = $member['integral'];

        $coupon_integral = array_sum(array_column($atv['goods_info'],'integral'));

        if($user_integral<$coupon_integral){

            return $check_type==1?0:2;
        }


        $dis = [

            'user_id'         => $user_id,

            'integral_atv_id' => $atv['id'],

            'type'            => $type,

            'refund'          => 0
        ];

        $num = $i_model->where($dis)->sum('num');

//        if($type==3){
//
//            $dis['type'] = 5;
//            //取消订单的数量
//            $del_num = $i_model->where($dis)->sum('num');
//
//            $num -=$del_num;
//        }

        if($num+$number>$atv['user_limit']){

            return $check_type==1?0:3;

        }

        return 1;
    }



    /**
     * @author chenniang
     * @DataTime: 2022-01-21 14:59
     * @功能说明:积分商城
     *
     */
    public function DoAtvPrice($input,$spe,$goods){

        $atv = $this->buyLimit($goods['id'],$spe['id']);

        if(!empty($atv)){
            //商品原来对价格
            $spe['i_goods_price'] = $spe['price'];

            $spe['i_price']  = $spe['price'] - $atv['price'];

            $spe['price']    = $atv['price'];

            $spe['integral_price'] = $atv['price'];

            $spe['integral'] = $atv['integral'];

        }

        $data['spe']   = $spe;

        $data['goods'] = $goods;

        return $data;

    }

    /**
     * @author chenniang
     * @DataTime: 2021-02-01 16:43
     * @功能说明:积分活动下单
     */
    public function DoAtv($input){

        if(!empty($input['is_integral'])){

            if(!empty($input['collage_id'])){

                return ['code'=>500,'msg'=>'积分活动商品不能拼团'];

            }

            if(!empty($input['bargain_id'])){

                return ['code'=>500,'msg'=>'积分活动商品不能砍价'];

            }

            $atv = $this->buyLimit($input['goods_info']['id'],$input['spe']['id']);

            if(!empty($atv)){

                $check = $this->getDataCondition($input['user_id'],$atv,$input['number'],3,2);

                if($check!=1){

                    $msg = $check==2?'积分不足':'超出兑换限制';

                    return ['code'=>500,'msg'=>$msg];
                }

                if($atv['have_stock']+$input['number']>$atv['stock']){

                    return ['code'=>500,'msg'=>'可兑换数量不足'];

                }

                $data['i_price']  = $input['spe']['price'] - $atv['price'];

                $data['price']    = $atv['price'];

                $data['integral'] = $atv['integral'];

                $data['integral_atv_id'] = $atv['id'];

                $data['integral_goods_id'] = $atv['shop_goods_id'];
                //添加到积分活动记录表
                $i_model = new \app\member\model\Integral();

                $i_record_id = $i_model->integralUserAdd($input['user_id'],$atv['integral']*-1*$input['number'],$atv['uniacid'],1,3,$input['order_id'],$atv['id'],$input['number'],0,0,$atv['shop_goods_id']);

                if($i_record_id!=0){

                    $data['i_record_id'] = $i_record_id;

                }else{

                    return ['code'=>500,'msg'=>'积分抵扣失败'];

                }

                return $data;

            }


        }

        return [];

    }









}